package com.example.demo.rocketmq;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

public class consumer1 {

    /**
     * 批量消费消息
     * @param args
     * @throws MQClientException
     */
    public static void main(String[] args) throws MQClientException {
        System.out.println("消费者启动开始");
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("consumer-group");
        consumer.setNamesrvAddr("192.168.1.102:9876");
        consumer.setPullInterval(10000);
        consumer.setConsumeThreadMin(5);
        consumer.setConsumeThreadMax(10);
        //指定批量消费的最大值，默认是1
        consumer.setConsumeMessageBatchMaxSize(200);
        //批量拉取消息的数量，默认是32 除了在这里设置还要在brocker配置文件设置 maxTransferCountOnMessageInMemory
        consumer.setPullBatchSize(100);

        consumer.subscribe("topic1", "*");
        //批量消费
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                System.out.println("一次批量消费消息数量：" + list.size());
                for (MessageExt msg : list) {
                    System.out.println("消息：" + new String(msg.getBody()));
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        consumer.start();
    }
}
